import React, { Component, Fragment } from "react";
import { Input, Form, Row, Col, Button, Select, Checkbox } from "antd";
import apis from "./pushSceneApi";
import styles from "./PushSceneAdd.less";

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const CheckboxGroup = Checkbox.Group;

@Form.create()
class PushSceneAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sceneTypeList: [],
      contentList: [],
      message: ""
    };
  }

  componentDidMount() {
    this.init();
  }

  init = async () => {
    const { dataSource: { sceneType } = {} } = this.props;
    const { id: sceneTypeId } = (await this.getSceneType()) || {};
    this.setSceneType(sceneType || sceneTypeId);
  };

  getSceneType = async () => {
    const { data: sceneTypeList = [] } = await apis.getSceneType();
    this.setState({ sceneTypeList });
    return sceneTypeList[0];
  };

  setSceneType = SceneType => {
    const {
      form: { setFieldsValue }
    } = this.props;
    setFieldsValue({ sceneType: SceneType });
    if (SceneType !== "G") {
      this.getContentList(SceneType);
    }
  };

  onSceneTypeChange = SceneType => {
    // 自定义模型场景
    if (SceneType !== "G") {
      this.getContentList(SceneType);
      this.setContent([]);
    }
  };

  getContentList = async SceneType => {
    const { data: contentList = [] } = await apis.getPushContent(SceneType);
    this.setState({ contentList });
  };

  setContent = content => {
    const { setFieldsValue } = this.props.form;
    setFieldsValue({
      content
    });
    this.onContentChange(content);
  };

  onContentChange = value => {
    const { contentList = [] } = this.state;
    let temp = "";
    contentList.forEach(({ dataValue, messageTemplate }) => {
      if (value.includes(dataValue)) {
        temp += `${messageTemplate};`;
      }
    });
    this.setState({ message: temp });
    this.setContentExample(undefined, temp);
  };

  setContentExample = (prefix, middle, suffix) => {
    const { getFieldValue, setFieldsValue } = this.props.form;
    const { message } = this.state;
    const pre =
      prefix === undefined ? getFieldValue("contnetPrefix") || "" : prefix;
    const mid = middle === undefined ? message : middle;
    const suf =
      suffix === undefined ? getFieldValue("contentSuffix") || "" : suffix;
    setFieldsValue({
      contentExample: `${pre}${mid}${suf}`
    });
  };

  handleOk = () => {
    const {
      dataSource,
      form: { validateFields },
      dispatch
    } = this.props;
    validateFields((err, values = {}) => {
      if (err) {
        return;
      }
      if (dataSource && dataSource.id) {
        const params = {
          ...values,
          id: dataSource.id
        };
        dispatch({
          type: "pushScene/pushSceneAdd",
          payload: params
        });
      } else {
        dispatch({
          type: "pushScene/pushSceneAdd",
          payload: values
        });
      }
    });
  };

  render() {
    const {
      dataSource: {
        id,
        sceneName,
        sceneType,
        sceneCode,
        comment,
        content,
        contnetPrefix,
        contentSuffix,
        contentExample
      } = {},
      form: { getFieldDecorator, getFieldsValue },
      closeModal
    } = this.props;
    const { sceneTypeList = [], contentList = [] } = this.state;
    const { sceneType: sceneTypeValue } = getFieldsValue();
    return (
      <div className={styles.root}>
        <div className={styles.title}>{id ? "编辑场景" : "新增场景"}</div>
        <Form layout="inline">
          <Row>
            <Row>
              <Col md={24} lg={12}>
                <FormItem
                  label={"场景名称"}
                  className={`${styles.selectTitle} ${styles.twoItem}`}
                >
                  {getFieldDecorator("sceneName", {
                    rules: [
                      {
                        required: true,
                        message: "请输入场景名称!"
                      },
                      {
                        pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
                        message: "场景名称含非法字符!"
                      }
                    ],
                    initialValue: sceneName
                  })(<Input />)}
                </FormItem>
              </Col>
              <Col md={24} lg={12}>
                <FormItem
                  label={"场景类型"}
                  className={`${styles.selectTitle} ${styles.twoItem}`}
                >
                  {getFieldDecorator("sceneType", {
                    rules: [
                      {
                        required: true,
                        message: "请选择场景类型!"
                      }
                    ],
                    initialValue: sceneType
                  })(
                    <Select onChange={this.onSceneTypeChange}>
                      {sceneTypeList.map(({ valueDesc, id: sceneTypeId }) => (
                        <Option value={sceneTypeId} key={sceneTypeId}>
                          {valueDesc}
                        </Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Col md={24} lg={12}>
              <FormItem
                label={"场景编码"}
                className={`${styles.selectTitle} ${styles.twoItem}`}
              >
                {getFieldDecorator("sceneCode", {
                  rules: [
                    {
                      pattern: /^[a-zA-Z0-9_]+$/,
                      message: "场景编码含非法字符!"
                    }
                  ],
                  initialValue: sceneCode
                })(<Input />)}
              </FormItem>
            </Col>
            <Col span={24}>
              <FormItem
                label={"场景描述"}
                className={`${styles.selectTitle} ${styles.oneItem}`}
              >
                {getFieldDecorator("comment", {
                  rules: [
                    {
                      required: true,
                      message: "请输入场景描述!"
                    }
                  ],
                  initialValue: comment
                })(
                  <TextArea
                    placeholder="请输入场景描述,300字以内"
                    rows={4}
                    maxLength={300}
                  />
                )}
              </FormItem>
            </Col>
            {sceneTypeValue !== "G" && (
              <Fragment>
                <Col span={24}>
                  <FormItem
                    label={"推送内容"}
                    className={`${styles.selectTitle} ${styles.oneItem}`}
                  >
                    {getFieldDecorator("content", {
                      rules: [
                        {
                          required: true,
                          message: "请选择推送内容!"
                        }
                      ],
                      initialValue: content ? content.split(",") : []
                    })(
                      <CheckboxGroup
                        onChange={this.onContentChange}
                        options={contentList.map(({ dataValue }) => ({
                          label: dataValue,
                          value: dataValue
                        }))}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col span={24}>
                  <FormItem
                    label={"推送内容前缀"}
                    className={`${styles.selectTitle} ${styles.oneItem}`}
                  >
                    {getFieldDecorator("contnetPrefix", {
                      initialValue: contnetPrefix
                    })(
                      <TextArea
                        onChange={e => {
                          this.setContentExample(e.target.value || "");
                        }}
                        placeholder="请输入推送内容前缀,30字以内"
                        rows={4}
                        maxLength={30}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col span={24}>
                  <FormItem
                    label={"推送内容后缀"}
                    className={`${styles.selectTitle} ${styles.oneItem}`}
                  >
                    {getFieldDecorator("contentSuffix", {
                      initialValue: contentSuffix
                    })(
                      <TextArea
                        onChange={e => {
                          this.setContentExample(
                            undefined,
                            undefined,
                            e.target.value || ""
                          );
                        }}
                        placeholder="请输入推送内容后缀,30字以内"
                        rows={4}
                        maxLength={30}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col span={24}>
                  <FormItem
                    label={"推送内容示例"}
                    className={`${styles.selectTitle} ${styles.oneItem}`}
                  >
                    {getFieldDecorator("contentExample", {
                      initialValue: contentExample
                    })(<TextArea disabled rows={4} />)}
                  </FormItem>
                </Col>
              </Fragment>
            )}
          </Row>
        </Form>
        <div className={styles.btnGroup}>
          <Button onClick={closeModal}>取消</Button>
          <Button type="primary" onClick={this.handleOk}>
            保存
          </Button>
        </div>
      </div>
    );
  }
}

export default PushSceneAdd;
